import React, {useContext, useEffect, useState} from 'react';
import {Select} from 'antd';
import './index.less';
import {ResultContext} from "../context";
import {PROJECT_ZONE_CODE} from "@/utils/utils.ts";

function CompareAreaSelect({ state, dispatch, width, type: pageType, onChange }: any) {
  const { state, dispatch } = useContext<any>(ResultContext)
  const [options, setOptions] = useState([]);
  const zoneCode = PROJECT_ZONE_CODE
  const { provinceOptions: province, cityOptions: city, zoneCodes } = state;

  const handleChange = (value: any) => {
    judgeOptionsDisabled(value);
    dispatch({
      zoneCodes: value
    })
  };
  const judgeOptionsDisabled = (value: any) => {
    if (value.length >= 5) {
      options.forEach((item: any) => {
        if (pageType == 'province' && item.value.indexOf(zoneCode) != -1) {
          item.disabled = true;
        } else if (value.includes(item.value)) {
          item.disabled = false;
        } else {
          item.disabled = true;
        }
      });
    } else if (value.length === 1) {
      options.forEach((item: any) => {
        if (value.includes(item.value)) {
          item.disabled = true;
        } else {
          item.disabled = false;
        }
      });
    } else {
      options.forEach((item: any) => {
        if (pageType == 'province' && item.value.indexOf(zoneCode) != -1) {
          item.disabled = true;
        } else {
          item.disabled = false;
        }
      });
    }
    setOptions(options);
  };
  useEffect(() => {
    let valueList: any = [];
    if (pageType === 'province') {
      setOptions(
        province?.map((item: any) => {
          if (item.value.indexOf(zoneCode) != -1) {
            item.disabled = true;
          } else {
            item.disabled = false;
          }
          return item;
        }),
      );
      province &&
        province.forEach((item: any) => {
          if (item.value.indexOf(zoneCode) != -1) {
            if (valueList.length >= 3) {
              valueList.pop();
            }
            valueList.push(item.value);
          } else if (valueList.length < 3) {
            valueList.push(item.value);
          }
        });
    }
    if (pageType === 'city') {
      setOptions(city);
      city &&
        city.forEach((item: any, index: any) => {
          if (index < 3) {
            valueList.push(item.value);
          }
        });
    }
    dispatch({
      zoneCodes: valueList
    })
  }, [province, city]);
  return (
    <Select
      showSearch
      mode="multiple"
      className="compare-area-select"
      style={{ width: width || 900 }}
      placeholder={pageType === 'city' ? '请选择对比地市' : '请选择对比省份'}
      size="small"
      maxTagCount="responsive"
      onChange={handleChange}
      options={options}
      value={zoneCodes}
      filterOption={(input: any, option: any) => option.label.indexOf(input) >= 0}
    ></Select>
  );
}

export default CompareAreaSelect
